<?php
/**
 * User: 五哥派
 * Date: 2024/7/17
 * Tel(同WX): 17335592719
 */
namespace app\api\service\auth;

use app\api\service\BaseService;
use app\api\service\user\Oauth as OauthService;
use app\common\lib\exception\BaseException;
use app\common\lib\wechat\WxUser;

class Party extends BaseService
{

    /**
     * 获取微信小程序登录态(session)
     * 这里支持静态变量缓存, 用于实现第二次调用该方法时直接返回已获得的session
     * @param string $code
     * @return array|false
     * @throws BaseException
     */
    public static function getMpWxSession(string $code)
    {
        static $session;
        if (empty($session)) {
            try {
                // 微信小程序通过code获取session
                $session = self::wxCode2Session($code);
            } catch (BaseException $e) {
                // showError参数表示让前端显示错误
                throwError($e->getMessage());
            }
        }
        return $session;
    }


    /**
     * 微信小程序通过code获取session (openid session_key unionid)
     * @param string $code
     * @return array|false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function wxCode2Session(string $code)
    {
        // 获取当前小程序信息
        $wxConfig = static::getMpWxConfig();
        // 微信登录 (获取session_key)
        $WxUser = new WxUser($wxConfig['app_id'], $wxConfig['app_secret']);
        $result = $WxUser->jscode2session($code);
        !$result && throwError($WxUser->getError());
        return $result;
    }

    /**
     * 获取微信小程序配置项
     * @return array
     * @throws \cores\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private static function getMpWxConfig(): array
    {
        //$wxConfig = WxappSettingModel::getWxappConfig();
        //if (empty($wxConfig['app_id']) || empty($wxConfig['app_secret'])) {
        //    throwError('请到后台小程序设置填写AppID和AppSecret参数');
        //}
        $wxConfig = [
            'app_id' => config('wx.app_id'),
            'app_secret' => config('wx.app_secret'),
        ];

        return $wxConfig;
    }
}